// frames = (i * fps) / 60 \ The Golden
// frames = frames % fps   /   Formula

// Fix it!!! Display timecode onStart() after quit!!!

package com.lalu.clapperboard;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.media.MediaPlayer;
import android.widget.TextView;
import android.graphics.Typeface;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import java.util.Calendar;

public class Clapperboard extends Activity {	
	int state = 0;
	Button screws;
	TextView txt;
	TextView txt_bg;
	TextView director;
	TextView title;
	TextView cameraman;
	TextView roll;
	TextView scene;
	TextView take;
	TextView fps;
	TextView date;
	Calendar currDate;
	TextView location;
	long std;

	Boolean resume = false;
	
	Boolean reset = false;
		
	long i = 60;
	
	int id = android.os.Process.myPid(); 
	
	private Handler mHandler = new Handler();
	
	private int mYear;
	private int mMonth;
	private int mDay;
	
	public String MILLISECONDS;
	
	final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
	final String file_name = "clapperboard.txt";
	
	

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/digital.ttf");
        Typeface tfl = Typeface.createFromAsset(getAssets(), "fonts/lalu_2.ttf");
        txt = (TextView) findViewById(R.id.txt);
        txt.setTypeface(tf);
        txt_bg = (TextView) findViewById(R.id.txt_bg);
        txt_bg.setTypeface(tf);
        director = (TextView) findViewById(R.id.director);
        director.setTypeface(tfl);
        title = (TextView) findViewById(R.id.title);
        title.setTypeface(tfl);
        cameraman = (TextView) findViewById(R.id.cameraman);
        cameraman.setTypeface(tfl);
        fps = (TextView) findViewById(R.id.fps);
        fps.setTypeface(tfl);
        date = (TextView) findViewById(R.id.date);
        date.setTypeface(tfl);
        location = (TextView) findViewById(R.id.location);
        location.setTypeface(tfl);
        roll = (TextView) findViewById(R.id.roll);
        roll.setTypeface(tfl);
        scene = (TextView) findViewById(R.id.scene);
        scene.setTypeface(tfl);
        take = (TextView) findViewById(R.id.take);
        take.setTypeface(tfl);
    	screws = (Button) findViewById(R.id.screws);
    	screws.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ rotate(); }});
    	
    	final Calendar c = Calendar.getInstance();
    	mYear = c.get(Calendar.YEAR);
    	mMonth = c.get(Calendar.MONTH);
    	mDay = c.get(Calendar.DAY_OF_MONTH);
    	date.setText(
    			new StringBuilder()
    			.append(mDay).append("/")
    			.append(mMonth + 1).append("/")
                .append(mYear).append(" ")
    			);
    }
    
    public void rotate() {
    	ImageView bar = (ImageView) findViewById(R.id.bar);
    	MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.clap);
    	mp.setLooping(false);
    	switch(state) {
    		case 0:
    			state = 1;
    			read_millis();
    			save_file();
    			bar.setImageResource(R.drawable.bar_down);
    			mp.start();
    			if (!resume) {
	    			mHandler.removeCallbacks(mUpdateTimeTask);
	    			mHandler.postDelayed(mUpdateTimeTask, 1);
	    			break;
    			}
    			else {
    				//mHandler.removeCallbacks(mUpdateTimeTask);
	    			mHandler.postDelayed(mUpdateTimeTask, 1);
	    			break;
    			}
    		case 1:
    			bar.setImageResource(R.drawable.bar_up);
    			state = 0;
    			mHandler.removeCallbacks(mUpdateTimeTask);
    			resume = true;
    			write_millis();
    			break;
    		}
    	}
    
	Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			i++;
			txt.setText(formatTime(i));
			mHandler.postDelayed(this, 1);
		}
	};
	// Time format
	
	// frames = (i * fps) / 60
	// frames = frames % fps
    public String formatTime(long i) {
          String output = "00:00:00:00";
	  	  long seconds = i / 60;
	  	  long minutes = seconds / 60;
	  	  long hours = minutes / 60;
	  	  long frames = (i * std) / 60;
	  	  
	  	  seconds = seconds % 60;
	  	  minutes = minutes % 60;
	  	  hours = hours % 60;
	  	  frames = frames % std;
	
	  	  String secondsD = String.valueOf(seconds);
	  	  String minutesD = String.valueOf(minutes);
	  	  String hoursD = String.valueOf(hours); 
	  	  String framesD = String.valueOf(frames);
	
	  	  if (seconds < 10)
	  	    secondsD = "0" + seconds;
	  	  if (minutes < 10)
	  	    minutesD = "0" + minutes;
	  	  if (hours < 10)
	  	    hoursD = "0" + hours;
	  	  if (frames < 10)
	  	    framesD = "0" + frames;
	
	  	  output = hoursD + ":" + minutesD + ":" + secondsD + ":" + framesD;
	  	  return output;
  	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
  	  super.onCreateOptionsMenu(menu);
  	  MenuItem item1 = menu.add("Settings");
  	  MenuItem item2 = menu.add("Save");
  	  MenuItem item3 = menu.add("Quit");
  	  return(super.onCreateOptionsMenu(menu)); //true
    }
    
    public void read_millis() {
    		try {
    			 String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getString(R.string.package_name)+"/files/";
    	    	 String fname = "millis.txt";
    			 BufferedReader fIn = new BufferedReader(new FileReader(path + fname));
    			 i = Long.valueOf(fIn.readLine());
    			 fIn.close();
    			 /*
    			 Context context = getApplicationContext();
       	         int duration = Toast.LENGTH_SHORT;
       	         Toast toast = Toast.makeText(context, "MILLIS read from " + path + fname + ".", duration);
       	         toast.show();
       	         */
    		}
    		catch (IOException ioe) {
                ioe.printStackTrace();
    			}
    }
    
    public void write_millis() {
    	String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getString(R.string.package_name)+"/files/";
    	String fname = "millis.txt";
    	// Current state of the external media
        String extState = Environment.getExternalStorageState();

        // External media can be written onto
        if (extState.equals(Environment.MEDIA_MOUNTED)) {
    	 try {
             // Make sure the path exists
             boolean exists = (new File(path)).exists();  
             if (!exists){ new File(path).mkdirs(); }  

             // Open output stream
             FileWriter gOut = new FileWriter(path + fname, false);

             gOut.write(String.valueOf(i));

             // Close output stream
             gOut.flush();
             gOut.close();
             /*
             Context context = getApplicationContext();
   	         int duration = Toast.LENGTH_SHORT;
   	         Toast toast = Toast.makeText(context, "MILLIS wrote to " + path + fname + ".", duration);
   	         toast.show();
   	         */
         } 
    	 catch (IOException ioe) {
             ioe.printStackTrace();
         }
        }
    }
    
    public void save_file() {
    	String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    	// Current state of the external media
        String extState = Environment.getExternalStorageState();

        // External media can be written onto
        if (extState.equals(Environment.MEDIA_MOUNTED)) {
    	if (i == 0) {
  		try {
  			final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  			FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
  			FileOutputStream fOut = new FileOutputStream("/sdcard/clapperboard.txt");
  	        fOut.write(String.valueOf("Title: " + prefs.getString("TITLE", "") + "\n" + "\n").getBytes());
  	        fOut.write(String.valueOf("Director: " + prefs.getString("DIRECTOR", "") + "\n" + "\n").getBytes());
  	        fOut.write(String.valueOf("Cameraman: " + prefs.getString("CAMERAMAN", "") + "\n" + "\n").getBytes());
  	        fOut.write(String.valueOf("Standard: " + prefs.getString("STANDARD", "") + "\n" + "\n").getBytes());
  	        gOut.append("\n" + formatTime(i) + "\n" + "\n");
  	        fOut.flush();
  	        gOut.flush();
  	        fOut.close();
  	        gOut.close();
  	        /*
  	        Context context = getApplicationContext();
  	        int duration = Toast.LENGTH_SHORT;
  	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + file_name + ".", duration);
  	        toast.show();
  	        */
  			}
  			catch (IOException ioe) {
              ioe.printStackTrace();
  			}
    	}
    	else {
    		try {
    			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    			FileWriter gOut = new FileWriter("/sdcard/clapperboard.txt", true);
    			gOut.append("\n" + "\n" + "ROLL " + prefs.getString("ROLL", "1") + " SCENE " + prefs.getString("SCENE", "1") + " TAKE " + prefs.getString("TAKE", "1") + "\n" + "\n");
    			gOut.append(formatTime(i) + "\n" + "\n");
    			gOut.flush();
      	        gOut.close();
      	        /*
      	        Context context = getApplicationContext();
    	        int duration = Toast.LENGTH_SHORT;
    	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + file_name + ".", duration);
    	        toast.show();
    	        */
    		}
    		catch (IOException ioe) {
                ioe.printStackTrace();
    			}
    		}
    	}
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
  	  if (item.getTitle() == "Quit") {
  		  write_millis();
  		  save_file();
  		  Process.killProcess(id);
  	  }
  	  if (item.getTitle() == "Save") {
			save_file();
			Context context = getApplicationContext();
	        int duration = Toast.LENGTH_SHORT;
	        Toast toast = Toast.makeText(context, "File saved to " + path + "/" + file_name + ".", duration);
	        toast.show();
  	  }
  	  if (item.getTitle() == "Settings") {
  		startActivity(new Intent(this, Preferences.class));
  		return true;
  	  }
  	  return(super.onOptionsItemSelected(item));
    }
    
    public void onResume() {
    	super.onResume();
    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    	std = Long.valueOf(prefs.getString("STANDARD", "25"));
    	roll.setText(prefs.getString("ROLL", "1"));
    	scene.setText(prefs.getString("SCENE", "1"));
    	take.setText(prefs.getString("TAKE", "1"));
    	director.setText(prefs.getString("DIRECTOR", null));
    	title.setText(prefs.getString("TITLE", null));
    	cameraman.setText(prefs.getString("CAMERAMAN", null));
    	//fps.setText(prefs.getString("STANDARD", "PAL"));
    	fps.setText(String.valueOf(std));
    	location.setText(prefs.getString("LOCATION", "INT"));
 		try {
   			 //String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getString(R.string.package_name)+"/files/";
   	    	 //String fname = "millis.txt";
   			 BufferedReader fIn = new BufferedReader(new FileReader("/sdcard/Android/data/com.lalu.clapperboard/files/millis.txt"));
   			 i = Long.valueOf(fIn.readLine());
   			 txt.setText(formatTime(i));
   			 fIn.close();
   			 /*
   			 Context context = getApplicationContext();
      	     int duration = Toast.LENGTH_SHORT;
      	     Toast toast = Toast.makeText(context, "MILLIS read from " + "/sdcard/Android/data/com.android.clapperboard/files/millis.txt" + ".", duration);
      	     toast.show();
      	     */
   		}
   		catch (IOException ioe) {
               ioe.printStackTrace();
   		}
   }
    
    /*
	public void onStart() {
		super.onStart();
		try {
  			 //String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getString(R.string.package_name)+"/files/";
  	    	 //String fname = "millis.txt";
  			 BufferedReader fIn = new BufferedReader(new FileReader("/sdcard/Android/data/com.lalu.clapperboard/files/millis.txt"));
  			 i = Long.valueOf(fIn.readLine());
  			 txt.setText(formatTime(i));
  			 fIn.close();
  			 Context context = getApplicationContext();
     	     int duration = Toast.LENGTH_SHORT;
     	     Toast toast = Toast.makeText(context, "MILLIS read from " + "/sdcard/Android/data/com.lalu.clapperboard/files/millis.txt" + ".", duration);
     	     toast.show();
  		}
  		catch (IOException ioe) {
              ioe.printStackTrace();
  		}
	}
	*/
}

